package cgs_bim

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/base"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"net/http"
	"strings"
)

func init() {
	server.Post("/api/bim/Save", Save, "添加或保存bim", server.Login)
	server.Post("/api/bim/Delete", Delete, "删除bim", server.Login)
	//server.Get("/api/earth/List", List, "获取工程列表", server.None)
	server.Get("/api/bim/Get", Get, "获取bim", server.None)

}


func Save(w http.ResponseWriter, r *http.Request) {
	bim := &Bim{}
	err := helper.ReadRequestBody(bim, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	dataUserModel := base.GenerateDataUserModel(bim, r)
	cgsService := NewBimService()
	err = cgsService.Save(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	_, _ = helper.WriteJSON(w, server.OK("Saved successfully!").WithData(bson.M{
		"id": bim.ID,
	}))
}


func Delete(w http.ResponseWriter, r *http.Request) {
	id, err := primitive.ObjectIDFromHex(r.FormValue("ID"))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("ID is not allowed."))
		return
	}
	bim := &Bim{
		ID:     id,
	}
	dataUserModel := base.GenerateDataUserModel(bim, r)
	cgsService := NewBimService()
	err = cgsService.Remove(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Delete successfully!"))
}


func Get(w http.ResponseWriter, r *http.Request) {
	id, err := primitive.ObjectIDFromHex(strings.TrimSpace(r.FormValue("ID")))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("ID is not allowed to be empty."))
		return
	}
	bim := &Bim{
		ID:     id,
	}
	dataUserModel := base.GenerateDataUserModel(bim, r)
	cgsService := NewBimService()
	result, err := cgsService.GetOne(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK().WithData(result))
}
